﻿using Huasky.MyWrod.Common.Util;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client;

namespace Huasky.MyWrod.Common.Rabbitmq;

public class MQConn
{
	internal IConnectionFactory ConnFactory { get; }

	private MQConn()
	{
		ConnFactory = new ConnectionFactory
		{
			Uri                      = new Uri(AppConfig.Settings.RabbitmqConnection),
			AutomaticRecoveryEnabled = true,
			NetworkRecoveryInterval  = TimeSpan.FromSeconds(10),
		};
	}


	/// <summary>
	/// 创建channel， 如果连接服务器失败，则一直重连
	/// </summary>
	public async Task<IModel> CreateChannel()
	{
		while (true)
		{
			try
			{
				var conn = ConnFactory.CreateConnection();
				return conn.CreateModel();
			}
			catch (Exception ex)
            {
                LoggerHelper.Error("Rabbitmq连接异常: {msg}", ex.Message);
                await Task.Delay(15_000);
			}
		}
	}

	public static MQConn Huasky  { get; } = new();
}